// pages/map/planningMap.js
//qqmap-wx-jssdk.min.js
// 引入SDK核心类
var QQMapWX = require('../components/qqmap-wx-jssdk.min.js');
var util = require('../../utils/util.js');

// 实例化API核心类
var map = new QQMapWX({
  key: 'D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    latitude: null,
    longitude: null,
    tolatitude: 39.828050,
    tolongitude: 116.436195,
    speed: null,
    accuracy: 6,
    key: "D2KBZ-BTFHF-PNCJN-NFUUW-K4G56-DNFBW",
    result: {
      duration: 0,
      distance: 0,
      locStart: '',
      locEnd: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.locatedAction();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //事件回调函数
  driving: function() {
    var _this = this;
    var from = "" + _this.data.latitude + "," + _this.data.longitude;
    var to = "" + _this.data.tolatitude + "," + _this.data.tolongitude;
    var key = _this.data.key;
    var url = 'https://apis.map.qq.com/ws/direction/v1/driving/?from=' + from + '&to=' + to + '&key=' + key;
    console.log(url);
    //网络请求设置
    var opt = {
      //WebService请求地址，from为起点坐标，to为终点坐标，开发key为必填
      url: url,
      method: 'GET',
      dataType: 'json',
      //请求成功回调
      success: function(res) {
        var ret = res.data
        if (ret.status != 0) return; //服务异常处理
        var coors = ret.result.routes[0].polyline,
          pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({
            latitude: coors[i],
            longitude: coors[i + 1]
          })
        }
        //设置polyline属性，将路线显示出来
        _this.setData({
          polyline: [{
            points: pl,
            color: '#FF0000DD',
            width: 2
          }]
        })
      }
    };
    wx.request(opt);
  },
  locatedAction: function() {
    var that = this;
    wx.getLocation({
      type: 'gcj02 ',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        that.setData({
          latitude: latitude,
          longitude: longitude,
          speed: speed,
          accuracy: accuracy
        })

        that.driving();
        that.calculateDinstance();
      }
    })
  },
  calculateDinstance: function() {
    var that = this;
    // 调用接口
    map.calculateDistance({
      mode: 'driving',
      to: [{
        latitude: that.data.tolatitude,
        longitude: that.data.tolongitude
      }],
      success: function(res) {
        console.log(res);
        that.setResultData(res.result.elements);
      },
      fail: function(res) {
        console.log(res);
      },
      complete: function(res) {
        console.log(res);
      }
    });
  },
  reverseGeocoder: function(latitude, longitude, kk) {
    var that = this;
    // 调用接口
    map.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function(res) {
        console.log(res);
      },
      fail: function(res) {
        console.log(res);
      },
      complete: function(res) {
        console.log(res);
        var address = res.result.address;
        console.log(address);
        if (kk == 'result.locStart') {
          that.setData({
            'result.locStart': address
          })
        } else {
          that.setData({
            'result.locEnd': address
          })
        }


        console.log(that.data);
      }
    });
  },
  setResultData: function(res) {
    var that = this;
    if (res != null && res.length > 0) {
      var item = res[0];
      var result = {};

      result['duration'] = util.formatSeconds(item.duration);
      result['distance'] = item.distance;

      that.reverseGeocoder(item.from.lat, item.from.lng, 'result.locStart');
      that.reverseGeocoder(item.to.lat, item.to.lng, 'result.locEnd');
      that.setData({
        result: result
      })
    }


  }
})